package com.competition.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.competition.entity.Admin;
import com.competition.resp.ResponseResult;
import com.competition.service.AdminService;
import com.competition.utils.jwt.JWTUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;


@RestController
@RequestMapping("/admin")
public class AdminLoginController {
    @Autowired
    private AdminService adminService;

    @PostMapping("/login")
    public ResponseResult<Object> login(@RequestBody Admin admin) {
        System.out.println(admin);
        if(admin.getAdminName() == null){
            return  new ResponseResult<Object>(400,"用户名不能为空");
        }
        if(admin.getAdminPassword() == null){
            return  new ResponseResult<Object>(400,"密码不能为空");
        }

        // 登录逻辑
        QueryWrapper<Admin> objectQueryWrapper = new QueryWrapper<Admin>();
        objectQueryWrapper.eq("admin_name", admin.getAdminName());
        objectQueryWrapper.eq("admin_password", admin.getAdminPassword());
        Admin user =  adminService.getOne(objectQueryWrapper);

        if(user == null){
            return  new ResponseResult<Object>(400,"用户名或密码错误");
        }
        HashMap<String, String> tokenMap = new HashMap<>();
        tokenMap.put("admin_id",user.getAdminId()+"");
        tokenMap.put("admin_name",user.getAdminName());
        tokenMap.put("admin_password",user.getAdminPassword());
        String token = JWTUtils.getToken(tokenMap);
        HashMap<String, Object> resMap = new HashMap<>();
        resMap.put("token",token);
        return new ResponseResult<Object>(200,"登录成功",resMap);
    }
}
